<template>
  <q-page class="q-pa-md">
    <!-- 字典类型管理 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section class="row items-center">
        <div class="text-h6">字典类型</div>
        <q-space />
        <q-btn color="primary" label="新增类型" icon="add" @click="showTypeAddDialog" />
      </q-card-section>

      <q-card-section>
        <q-table
          :rows="dictTypes"
          :columns="typeColumns"
          row-key="dictId"
          :loading="typeLoading"
          :pagination="typePagination"
          @request="loadDictTypes"
          binary-state-sort
          flat
          bordered
        >
          <!-- 状态列 -->
          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-toggle
                v-model="props.row.status"
                checked-icon="check"
                unchecked-icon="clear"
                :true-value="1"
                :false-value="0"
                color="green"
                @update:model-value="toggleTypeStatus(props.row)"
              />
            </q-td>
          </template>

          <!-- 操作列 -->
          <template v-slot:body-cell-actions="props">
            <q-td :props="props" class="q-gutter-x-sm">
              <q-btn dense color="primary" icon="edit" @click="showTypeEditDialog(props.row)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn
                dense
                color="negative"
                icon="delete"
                @click="confirmTypeDelete(props.row.dictId)"
              >
                <q-tooltip>删除</q-tooltip>
              </q-btn>
              <q-btn dense color="secondary" icon="list" @click="showDictData(props.row)">
                <q-tooltip>字典数据</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>

    <!-- 字典数据管理 -->
    <q-card flat bordered v-if="currentDictType">
      <q-card-section class="row items-center">
        <div class="text-h6">字典数据 - {{ currentDictType.dictName }}</div>
        <q-space />
        <q-btn color="primary" label="新增数据" icon="add" @click="showDataAddDialog" />
      </q-card-section>

      <q-card-section>
        <q-table
          :rows="dictData"
          :columns="dataColumns"
          row-key="dictCode"
          :loading="dataLoading"
          :pagination="dataPagination"
          @request="loadDictData"
          binary-state-sort
          flat
          bordered
        >
          <!-- 状态列 -->
          <template v-slot:body-cell-status="props">
            <q-td :props="props">
              <q-toggle
                v-model="props.row.status"
                checked-icon="check"
                unchecked-icon="clear"
                :true-value="1"
                :false-value="0"
                color="green"
                @update:model-value="toggleDataStatus(props.row)"
              />
            </q-td>
          </template>

          <!-- 操作列 -->
          <template v-slot:body-cell-actions="props">
            <q-td :props="props" class="q-gutter-x-sm">
              <q-btn dense color="primary" icon="edit" @click="showDataEditDialog(props.row)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn
                dense
                color="negative"
                icon="delete"
                @click="confirmDataDelete(props.row.dictCode)"
              >
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>

    <!-- 字典类型对话框 -->
    <q-dialog v-model="typeDialogVisible" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <div class="text-h6">{{ isTypeEdit ? '编辑字典类型' : '新增字典类型' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitTypeForm" class="q-gutter-md">
            <q-input
              v-model="typeForm.dictName"
              label="字典名称"
              :rules="[(val) => !!val || '字典名称不能为空']"
              outlined
            />

            <q-input
              v-model="typeForm.dictType"
              label="字典类型"
              :rules="[(val) => !!val || '字典类型不能为空']"
              outlined
              :readonly="isTypeEdit"
            />

            <q-select
              v-model="typeForm.status"
              label="状态"
              :options="statusOptions"
              outlined
              emit-value
              map-options
            />

            <q-input v-model="typeForm.remark" label="备注" type="textarea" outlined autogrow />

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isTypeEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 字典数据对话框 -->
    <q-dialog v-model="dataDialogVisible" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <div class="text-h6">{{ isDataEdit ? '编辑字典数据' : '新增字典数据' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitDataForm" class="q-gutter-md">
            <q-input
              v-model="dataForm.dictLabel"
              label="字典标签"
              :rules="[(val) => !!val || '字典标签不能为空']"
              outlined
            />

            <q-input
              v-model="dataForm.dictValue"
              label="字典键值"
              :rules="[(val) => !!val || '字典键值不能为空']"
              outlined
            />

            <q-input
              v-model="dataForm.dictSort"
              label="字典排序"
              type="number"
              :rules="[(val) => val >= 0 || '排序必须大于等于0']"
              outlined
            />

            <q-input v-model="dataForm.cssClass" label="样式属性" outlined />

            <q-input v-model="dataForm.listClass" label="表格回显样式" outlined />

            <q-select
              v-model="dataForm.status"
              label="状态"
              :options="statusOptions"
              outlined
              emit-value
              map-options
            />

            <q-input v-model="dataForm.remark" label="备注" type="textarea" outlined autogrow />

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isDataEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 字典类型表格列
const typeColumns = [
  { name: 'dictId', label: '字典ID', field: 'dictId', align: 'center', sortable: true },
  { name: 'dictName', label: '字典名称', field: 'dictName', align: 'center', sortable: true },
  { name: 'dictType', label: '字典类型', field: 'dictType', align: 'center' },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center', sortable: true },
  { name: 'actions', label: '操作', align: 'center' },
]

// 字典数据表格列
const dataColumns = [
  { name: 'dictCode', label: '字典编码', field: 'dictCode', align: 'center', sortable: true },
  { name: 'dictLabel', label: '字典标签', field: 'dictLabel', align: 'center' },
  { name: 'dictValue', label: '字典键值', field: 'dictValue', align: 'center' },
  { name: 'dictSort', label: '字典排序', field: 'dictSort', align: 'center', sortable: true },
  { name: 'cssClass', label: '样式属性', field: 'cssClass', align: 'center' },
  { name: 'listClass', label: '回显样式', field: 'listClass', align: 'center' },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'actions', label: '操作', align: 'center' },
]

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '停用', value: 0 },
]

// 字典类型数据
const dictTypes = ref([])
const typeLoading = ref(false)
const typePagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const typeDialogVisible = ref(false)
const isTypeEdit = ref(false)
const typeForm = ref({
  dictId: null,
  dictName: '',
  dictType: '',
  status: 1,
  remark: '',
})

// 字典数据
const currentDictType = ref(null)
const dictData = ref([])
const dataLoading = ref(false)
const dataPagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const dataDialogVisible = ref(false)
const isDataEdit = ref(false)
const dataForm = ref({
  dictCode: null,
  dictType: '',
  dictLabel: '',
  dictValue: '',
  dictSort: 0,
  cssClass: '',
  listClass: 'default',
  status: 1,
  remark: '',
})

// 初始化加载数据
onMounted(() => {
  loadDictTypes()
})

// 加载字典类型
function loadDictTypes(props) {
  if (!props) {
    props = { pagination: typePagination.value }
  }

  typeLoading.value = true
  const { page, rowsPerPage } = props.pagination

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      dictId: (page - 1) * rowsPerPage + i + 1,
      dictName: ['用户性别', '菜单状态', '系统开关', '任务状态', '通知类型'][i % 5],
      dictType: [
        'sys_user_sex',
        'sys_show_hide',
        'sys_normal_disable',
        'sys_job_status',
        'sys_notice_type',
      ][i % 5],
      status: Math.random() > 0.3 ? 1 : 0,
      createTime: new Date().toLocaleString(),
      remark: ['用户性别列表', '菜单状态列表', '系统开关列表', '任务状态列表', '通知类型列表'][
        i % 5
      ],
    }))

    dictTypes.value = mockData
    typePagination.value.rowsNumber = 50 // 模拟总条数
    typePagination.value.page = page
    typePagination.value.rowsPerPage = rowsPerPage
    typeLoading.value = false
  }, 500)
}

// 加载字典数据
function loadDictData(props) {
  if (!currentDictType.value) return

  if (!props) {
    props = { pagination: dataPagination.value }
  }

  dataLoading.value = true
  const { page, rowsPerPage } = props.pagination

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    let mockData = []

    if (currentDictType.value.dictType === 'sys_user_sex') {
      mockData = [
        {
          dictCode: 1,
          dictLabel: '男',
          dictValue: '0',
          dictSort: 1,
          cssClass: '',
          listClass: 'primary',
          status: 1,
        },
        {
          dictCode: 2,
          dictLabel: '女',
          dictValue: '1',
          dictSort: 2,
          cssClass: '',
          listClass: 'danger',
          status: 1,
        },
        {
          dictCode: 3,
          dictLabel: '未知',
          dictValue: '2',
          dictSort: 3,
          cssClass: '',
          listClass: 'warning',
          status: 1,
        },
      ]
    } else if (currentDictType.value.dictType === 'sys_show_hide') {
      mockData = [
        {
          dictCode: 4,
          dictLabel: '显示',
          dictValue: '1',
          dictSort: 1,
          cssClass: '',
          listClass: 'primary',
          status: 1,
        },
        {
          dictCode: 5,
          dictLabel: '隐藏',
          dictValue: '0',
          dictSort: 2,
          cssClass: '',
          listClass: 'danger',
          status: 1,
        },
      ]
    } else {
      mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
        dictCode: (page - 1) * rowsPerPage + i + 1,
        dictLabel: `标签${i + 1}`,
        dictValue: `${i}`,
        dictSort: i + 1,
        cssClass: '',
        listClass: ['primary', 'secondary', 'positive', 'negative', 'info', 'warning'][i % 6],
        status: Math.random() > 0.3 ? 1 : 0,
        remark: `备注${i + 1}`,
      }))
    }

    dictData.value = mockData
    dataPagination.value.rowsNumber = mockData.length // 模拟总条数
    dataPagination.value.page = page
    dataPagination.value.rowsPerPage = rowsPerPage
    dataLoading.value = false
  }, 500)
}

// 显示字典类型新增对话框
function showTypeAddDialog() {
  isTypeEdit.value = false
  typeForm.value = {
    dictId: null,
    dictName: '',
    dictType: '',
    status: 1,
    remark: '',
  }
  typeDialogVisible.value = true
}

// 显示字典类型编辑对话框
function showTypeEditDialog(row) {
  isTypeEdit.value = true
  typeForm.value = { ...row }
  typeDialogVisible.value = true
}

// 提交字典类型表单
function submitTypeForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isTypeEdit.value ? '字典类型已更新' : '字典类型创建成功',
  })
  typeDialogVisible.value = false
  loadDictTypes()
}

// 切换字典类型状态
function toggleTypeStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === 0 ? '启用' : '停用'}字典类型 ${row.dictName}  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `字典类型已${row.status === 0 ? '启用' : '停用'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
    })
}

// 确认删除字典类型
function confirmTypeDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该字典类型吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '字典类型已删除',
    })
    loadDictTypes()
  })
}

// 显示字典数据
function showDictData(row) {
  currentDictType.value = row
  dataForm.value.dictType = row.dictType
  loadDictData()
}

// 显示字典数据新增对话框
function showDataAddDialog() {
  if (!currentDictType.value) {
    $q.notify({
      type: 'warning',
      message: '请先选择字典类型',
    })
    return
  }

  isDataEdit.value = false
  dataForm.value = {
    dictCode: null,
    dictType: currentDictType.value.dictType,
    dictLabel: '',
    dictValue: '',
    dictSort: 0,
    cssClass: '',
    listClass: 'default',
    status: 1,
    remark: '',
  }
  dataDialogVisible.value = true
}

// 显示字典数据编辑对话框
function showDataEditDialog(row) {
  isDataEdit.value = true
  dataForm.value = { ...row }
  dataDialogVisible.value = true
}

// 提交字典数据表单
function submitDataForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isDataEdit.value ? '字典数据已更新' : '字典数据创建成功',
  })
  dataDialogVisible.value = false
  loadDictData()
}

// 切换字典数据状态
function toggleDataStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === 0 ? '启用' : '停用'}字典数据 ${row.dictLabel}  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `字典数据已${row.status === 0 ? '启用' : '停用'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
    })
}

// 确认删除字典数据
function confirmDataDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该字典数据吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '字典数据已删除',
    })
    loadDictData()
  })
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}

// 回显样式标签
.default {
  color: inherit;
}
.primary {
  color: #1976d2;
}
.secondary {
  color: #26a69a;
}
.positive {
  color: #21ba45;
}
.negative {
  color: #c10015;
}
.info {
  color: #31ccec;
}
.warning {
  color: #f2c037;
}
.danger {
  color: #f56c6c;
}
.success {
  color: #67c23a;
}
</style>
